package by.yativem.commons.utils.math;

public class DoubleMath implements IMath<Double> {
	
	private static DoubleMath instance;
	
	public static  DoubleMath getInstance(){
		if(instance == null){
			instance = new DoubleMath();
		}
		return instance;
	}

	@Override
	public Double add(Double o1, Double o2) {

		return o1 + o2;
	}

	@Override
	public Double invert(Double o) {

		return -1 * o;
	}

	@Override
	public Double division(Double o1, Double o2) {

		return o1/o2;
	}

	@Override
	public Double maltiplicate(Double o1, Double o2) {
		
		return o1*o2;
	}

	@Override
	public Double getZero() {
		
		return new Double(0);
	}

	@Override
	public int compare(Double o1, Double o2) {
		
		return o1.compareTo(o2);
	}
	
	public Byte[] convertToBitRepresent(Double o){		
		long lo  = o.longValue();		
		 Double d = Math.log(lo)/Math.log(2);
		int index =(int) Math.round(d + 0.5D);
		Byte[] result = new Byte[Long.SIZE];
		if(lo < 0 ){
			result[0] = 1;
		}else{
			result[0] = 0;
		}
		
		for(int i =  1; i < Long.SIZE - index; i++){
			result[i] = 0;
		}
		
		index = Long.SIZE - index;
	    while (lo >0) {	    	 
	    	if(lo  % 2 == 1){
	    		result[index] = 0;
	    	}else{
	    		result[index] = 1;
	    	}
	    	index++;
	    	lo = lo/2;   
	    }
		
	    return result;
	}
	
	public Byte[] convertToBitRepresent(Double o, int arrSize) throws Exception{		
		long lo  = o.longValue();		
		 Double d = Math.log(lo)/Math.log(2);
		int index =(int) Math.round(d + 0.5D);
		if(arrSize-1 < index){
			throw new Exception("The value");
		}
		Byte[] result = new Byte[arrSize];
		if(lo < 0 ){
			result[0] = 1;
		}else{
			result[0] = 0;
		}
		
		for(int i =  1; i < Long.SIZE - index; i++){
			result[i] = 0;
		}
		
		index = Long.SIZE - index;
	    while (lo >0) {	    	 
	    	if(lo  % 2 == 1){
	    		result[index] = 0;
	    	}else{
	    		result[index] = 1;
	    	}
	    	index++;
	    	lo = lo/2;   
	    }
		
	    return result;
	}
	
	public static String byteArrayToString(Byte[] b){
		StringBuilder sb = new StringBuilder();
		for(Byte bb : b){
			sb.append(bb);
		}
		return sb.toString();
	}
	
	public static void main(String[] arg){
		DoubleMath dm = new DoubleMath();
		
		Byte[] t1 = dm.convertToBitRepresent(12D);
		System.out.println(12D);
		System.out.println(		DoubleMath.byteArrayToString(t1));
	}

	@Override
	public Double convertToT(Object o) throws IllegalArgumentException {
		if ( o instanceof Byte){
			return ((Byte) o).doubleValue();
		}
		
		throw new IllegalArgumentException();
	}

}
